package com.hqyj.bigdata.hiveproject.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.bigdata.hiveproject.entity.TopTenVideoInfo;
import com.hqyj.bigdata.hiveproject.mapper.TopTenVideoInfoMapper;
import com.hqyj.bigdata.hiveproject.service.TopTenVideoInfoService;
import com.hqyj.bigdata.hiveproject.util.HiveConnection;
import com.hqyj.bigdata.hiveproject.util.HiveUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Service
public class TopTenVideoInfoServiceImpl extends ServiceImpl<TopTenVideoInfoMapper, TopTenVideoInfo> implements TopTenVideoInfoService {

    @Resource
    private TopTenVideoInfoMapper topTenVideoInfoMapper;

    @Transactional(rollbackOn = Exception.class)
    @Override
    public boolean initTopTenVideoInfoList() throws Exception {
        String sql = "select\n" +
                "  distinct (videoId),\n" +
                "  views\n" +
                "from \n" +
                "  gulivideo_orc\n" +
                "order by views desc\n" +
                "limit 10";

        PreparedStatement pstm = null;
        ResultSet rs = null;
        List<TopTenVideoInfo> topTenVideoInfos = new ArrayList<TopTenVideoInfo>();

        try {
            pstm = HiveConnection.getConnection().prepareStatement(sql);
            //boolean flag = pstm.execute(sql);

            rs = pstm.executeQuery(); //得到数据集
            while (rs.next()) {
                //System.out.println(rs.getString("videoid") + "," + rs.getLong("views"));
                TopTenVideoInfo topTenVideoInfo = TopTenVideoInfo.builder().videoId(rs.getString("videoid")).view(rs.getLong("views")).build();
                topTenVideoInfos.add(topTenVideoInfo);
            }

            return super.saveBatch(topTenVideoInfos);
        } catch (Exception ex) {
            ex.printStackTrace();
            // 事务的回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }

                if (pstm != null) {
                    pstm.close();
                    pstm = null;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }

    @Override
    public List<TopTenVideoInfo> queryTopTenVideoInfoList() throws Exception {

        return super.list(null);
    }
}
